﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XStudio.XCRF.Web.Controllers;
using System.Web.Routing;
using XStudio.XCRF.Web.Common.Sessions;
using XStudio.XCRF.Data.Business.Permissions;
using XStudio.XCRF.Data.Enums;

namespace XStudio.XCRF.Web.Filters
{
    /// <summary>
    /// 权限过滤器
    /// </summary>
    public class PermissionAttribute : FilterAttribute, IAuthorizationFilter
    {
        /// <summary>
        /// 创建新的权限过滤器
        /// </summary>
        public PermissionAttribute()
        {

        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            IEnumerable<BasePermissionAttribute> classAttrs = from obj in filterContext.Controller.GetType()
                                                             .GetCustomAttributes(typeof(BasePermissionAttribute), true)
                                                              select (BasePermissionAttribute)obj;
            IEnumerable<BasePermissionAttribute> methordAttrs = from obj in filterContext.ActionDescriptor
                                                                .GetCustomAttributes(typeof(BasePermissionAttribute), true)
                                                                select (BasePermissionAttribute)obj;
            PermissionAttributeAnalyzer analyzer = new PermissionAttributeAnalyzer(classAttrs, methordAttrs);

            //允许匿名访问则不进行后续判断
            if (analyzer.AllowAnonymous)
                return;
            //判断登陆
            if (!LoginSession.IsLoggedIn)
            {
                OnRequireLogin(filterContext);
                return;
            }
            MemberTypes memberType = (MemberTypes)LoginSession.MemberType;
            PermissionType permission = analyzer.Permissions[memberType];

            //判断权限
            if (permission == PermissionType.Deny)
                OnDeniedPermission(filterContext);
        }

        /// <summary>
        /// 当需要登陆时执行
        /// </summary>
        /// <param name="filterContext"></param>
        private void OnRequireLogin(AuthorizationContext filterContext)
        {
            //string backUrl = filterContext.HttpContext.Request.RawUrl;
            RouteValueDictionary values = ExpressionHelper2
                .GetRouteValues<MemberController>(c => c.MemberLogin());
            filterContext.Result = new RedirectToRouteResult(values);
        }

        /// <summary>
        /// 当权限禁止禁止时执行
        /// </summary>
        /// <param name="filterContext"></param>
        private void OnDeniedPermission(AuthorizationContext filterContext)
        {
            RouteValueDictionary values = ExpressionHelper2
                .GetRouteValues<MemberController>(c => c.NoPermission());
            filterContext.Result = new RedirectToRouteResult(values);
        }
    }
}